using System;
using System.Data;
using Microsoft.MetadirectoryServices;

namespace ILMXFrameWork.XMA
{
    /// <summary>
    /// The DataTableLDIFExporter takes the DataTable passed and generates a LDIF File.
    /// </summary>
     /*Copyright (c) 2009, Joseph Stepongzi
     All rights reserved.
     Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
     * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
     * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
     * Neither the name of Joseph Stepongzi nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
     THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY 
     AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 
     (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, 
     STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.  
      */
    public class DataTableLDIFExporter
    {
        // variables
        private System.Data.DataTable baseTable = null;
        private System.Data.DataTable multiValueTable = null;
        private System.IO.StreamWriter sw = null;
        private string filePath = null;
        private string anchor = null;
        private string objectClassAttribute = null;
        private System.Text.Encoding encoding;

        /// <summary>
        /// Constructor to export to LDIF from just a base table.
        /// </summary>
        /// <param name="baseTable">The base table data table to read from.</param>
        /// <param name="filePath">The filePath to write the data too.</param>
        /// <param name="types">The TypeDescriptionCollection that describes the attribute types and the anchor values.</param>
        /// <param name="objectClassAttribute">The attribute or column to use to describe the object type.</param>
        /// <param name="objectClassValue">The hardcoded object type value.</param>
        /// <param name="encoding">The encoding used to write to the file.</param>
        public DataTableLDIFExporter(System.Data.DataTable baseTable, string filePath, TypeDescriptionCollection types, string objectClassAttribute, string objectClassValue, System.Text.Encoding encoding)
        {
            this.baseTable = baseTable;
            this.filePath = filePath;
            this.objectClassAttribute = objectClassAttribute;
            this.encoding = encoding;

            sw = new System.IO.StreamWriter(filePath, false, encoding);

            for (int i = 0; i < baseTable.Rows.Count; i++)
            {
                System.Data.DataRow dr = baseTable.Rows[i];
                string attributeName = null;
                string attributeValue = null;
                string objectClass = null;

                if (objectClassAttribute == "" || objectClassAttribute == null)
                {
                    if (objectClassValue == "")
                    {
                        objectClass = "PERSON";
                    }
                    else
                    {
                        objectClass = objectClassValue;
                    }
                }
                else
                {
                    string objectClassAttributeValue = dr[objectClassAttribute].ToString();
                    objectClass = objectClassAttributeValue;
                }
                TypeDescription t = types[objectClass];
                if (t.AnchorAttributes.Count > 1)
                {
                    throw new TerminateRunException(String.Format("ObjectType {0} has more than one anchor attribute", objectClass));
                }
                foreach (AttributeDescription attr in t.AnchorAttributes)
                {
                    anchor = attr.Name.ToString();
                }
                string anchorValue = dr[anchor].ToString();
                sw.WriteLine("dn: CN=" + anchorValue);
                sw.WriteLine("OBJECTCLASS: " + objectClass);

                for (int x = 0; x < dr.Table.Columns.Count; x++)
                {
                    System.Data.DataColumn dc = dr.Table.Columns[x];
                    attributeName = dc.ColumnName.ToString();
                    attributeValue = dr[x].ToString();
                    if (!(attributeValue == ""))
                    {
                        attributeValue = attributeValue.Replace("\n", "").Replace("\r", " ");
                        if (!(attributeName == objectClassAttribute))
                        {
                            sw.WriteLine(attributeName + ": " + attributeValue);
                        }
                    }
                }
                sw.WriteLine("");
            }
            sw.Close();
        }

        /// <summary>
        /// Constructor to export to LDIF with a base table and multivalue table.
        /// </summary>
        /// <param name="baseTable">The base table data table to read from.</param>
        /// <param name="multiValueTable">The multiValue data table to read from.</param>
        /// <param name="filePath">The filePath to write the data too.</param>
        /// <param name="types">The TypeDescriptionCollection that describes the attribute types and the anchor values.</param>
        /// <param name="objectClassAttribute">The attribute or column to use to describe the object type.</param>
        /// <param name="objectClassValue">The hardcoded object type value.</param>
        /// <param name="multiValueAttributeColumn">The column in the multiValue table that tells what the multiValued attribute name should be.</param>
        /// <param name="multiValueValueColumn">The column in the multiValue table that tells what the multivalued attribute value should be.</param>
        /// <param name="encoding">The encoding used to write to the file.</param>
        public DataTableLDIFExporter(System.Data.DataTable baseTable, System.Data.DataTable multiValueTable, string filePath, TypeDescriptionCollection types, string objectClassAttribute, string objectClassValue, string multiValueAttributeColumn, string multiValueValueColumn, System.Text.Encoding encoding)
        {
            // variables
            this.baseTable = baseTable;
            this.multiValueTable = multiValueTable;
            this.filePath = filePath;
            this.objectClassAttribute = objectClassAttribute;
            this.encoding = encoding;

            sw = new System.IO.StreamWriter(filePath, false, encoding);

            for (int i = 0; i < baseTable.Rows.Count; i++)
            {
                System.Data.DataRow dr = baseTable.Rows[i];
                string attributeName = null;
                string attributeValue = null;
                string objectClass = null;

                if (objectClassAttribute == "" || objectClassAttribute == null)
                {
                    if (objectClassValue == "")
                    {
                        objectClass = "PERSON";
                    }
                    else
                    {
                        objectClass = objectClassValue;
                    }
                }
                else
                {
                    string objectClassAttributeValue = dr[objectClassAttribute].ToString();
                    objectClass = objectClassAttributeValue;
                }
                TypeDescription t = types[objectClass];
                if (t.AnchorAttributes.Count > 1)
                {
                    throw new TerminateRunException(String.Format("ObjectType {0} has more than one anchor attribute", objectClass));
                }
                foreach (AttributeDescription attr in t.AnchorAttributes)
                {
                    anchor = attr.Name.ToString();
                }
                string anchorValue = dr[anchor].ToString();
                sw.WriteLine("dn: CN=" + anchorValue);
                sw.WriteLine("OBJECTCLASS: " + objectClass);

                for (int x = 0; x < dr.Table.Columns.Count; x++)
                {
                    System.Data.DataColumn dc = dr.Table.Columns[x];
                    attributeName = dc.ColumnName.ToString();

                    attributeValue = dr[x].ToString();
                    if (!(attributeValue == ""))
                    {
                        attributeValue = attributeValue.Replace("\n", "").Replace("\r", " ");
                        if (!(attributeName == objectClassAttribute))
                        {
                            sw.WriteLine(attributeName + ": " + attributeValue);
                        }
                    }
                }
                foreach (AttributeDescription attr in t.Attributes)
                {
                    if (attr.IsMultiValued == true)
                    {
                        if (attr.DataType == AttributeType.Reference)
                        {
                            DataRow[] drCollection = multiValueTable.Select(anchor + "='" + anchorValue + "' and " + multiValueAttributeColumn + "='" + attr.Name.ToString() + "'");
                            if (drCollection.Length > 0)
                            {
                                foreach (DataRow multiValueRows in drCollection)
                                {
                                    sw.WriteLine(attr.Name.ToString() + ": CN=" + multiValueRows[multiValueValueColumn].ToString());
                                }
                            }
                        }
                        else
                        {
                            DataRow[] drCollection = multiValueTable.Select(anchor + "='" + anchorValue + "' and " + multiValueAttributeColumn + "='" + attr.Name.ToString() + "'");
                            if (drCollection.Length > 0)
                            {
                                foreach (DataRow multiValueRows in drCollection)
                                {
                                    sw.WriteLine(attr.Name.ToString() + ": " + multiValueRows[multiValueValueColumn].ToString());
                                }
                            }
                        }
                    }
                }
                sw.WriteLine("");
            }
            sw.Close();
        }
    }
}
